package controller

import (
	"doctor_api_backend/config"
	"doctor_api_backend/models"

	"github.com/gin-gonic/gin"
)

// 删除病历记录, 找到medical_record_code才删除成功，否者打印删除失败，不存在
func DeleteMedicalRecord(c *gin.Context) {
	medicalRecordCode := c.Param("medicalRecordCode")
	var record models.MedicalRecord
	if err := config.DB.Where("medical_record_code = ?", medicalRecordCode).First(&record).Error; err != nil {
		c.JSON(404, gin.H{"error": "病历记录不存在"})
		return
	}

	config.DB.Delete(&record)

	c.JSON(200, gin.H{"message": "病历记录删除成功"})

}

// 更新病历记录 通过medical_record_code更新病历记录
func UpdateMedicalRecord(c *gin.Context) {
	medicalRecordCode := c.Param("medicalRecordCode")
	var record models.MedicalRecord
	if err := config.DB.Where("medical_record_code = ?", medicalRecordCode).First(&record).Error; err != nil {
		c.JSON(404, gin.H{"error": "病历记录不存在"})
		return
	}

	var updatedRecord models.MedicalRecord
	if err := c.ShouldBindJSON(&updatedRecord); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	config.DB.Model(&record).Updates(updatedRecord)
	c.JSON(200, record)
}

// 创建病历记录
func CreateMedicalRecord(c *gin.Context) {
	var record models.MedicalRecord
	if err := c.ShouldBindJSON(&record); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	config.DB.Create(&record)
	c.JSON(201, record)
}

// 获取所有病历记录
func GetMedicalRecords(c *gin.Context) {
	var records []models.MedicalRecord
	config.DB.Find(&records)
	c.JSON(200, records)
}

// 获取单个病历记录 通过medical_record_code获取单个病历记录
func GetMedicalRecord(c *gin.Context) {
	medicalRecordCode := c.Param("medicalRecordCode")
	var record models.MedicalRecord
	config.DB.Where("medical_record_code = ?", medicalRecordCode).First(&record)
	c.JSON(200, record)
}

// 获取单个病历记录, 找到medical_record_code才获取成功，否者打印获取失败，不存在
func GetMedicalRecordByMedicalRecordCode(c *gin.Context) {
	medicalRecordCode := c.Param("medicalRecordCode")
	var record models.MedicalRecord
	if err := config.DB.Where("medical_record_code = ?", medicalRecordCode).First(&record).Error; err != nil {
		c.JSON(404, gin.H{"error": "病历记录不存在"})
		return
	}
	c.JSON(200, record)
}
